package com.yf.dxapp.module.app.controller.app;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import com.alibaba.fastjson.JSON;
import com.yf.dxapp.module.app.component.app.AppCourseComponent;
import com.yf.dxapp.module.app.component.app.QiniuFileComponent;
import com.yf.dxapp.module.app.controller.admin.appnotice.vo.AppNoticePageReqVO;
import com.yf.dxapp.module.app.controller.app.vo.AppCourseVo;
import com.yf.dxapp.module.app.controller.app.vo.BehaviorRequest;
import com.yf.dxapp.module.app.controller.app.vo.index.AppIndexVo;
import com.yf.dxapp.module.app.controller.app.vo.index.FunctionAreaVo;
import com.yf.dxapp.module.app.dal.dataobject.appbanner.AppBannerDO;
import com.yf.dxapp.module.app.dal.dataobject.appconfig.AppConfigDO;
import com.yf.dxapp.module.app.dal.dataobject.appnotice.AppNoticeDO;
import com.yf.dxapp.module.app.dal.dataobject.course.CourseDO;
import com.yf.dxapp.module.app.enums.app.AppStatusEnum;
import com.yf.dxapp.module.app.enums.app.BannerTypeEnum;
import com.yf.dxapp.module.app.service.appbanner.AppBannerService;
import com.yf.dxapp.module.app.service.appconfig.AppConfigService;
import com.yf.dxapp.module.app.service.appnotice.AppNoticeService;
import com.yf.dxapp.module.app.service.behavior.BehaviorService;
import com.yf.dxapp.module.app.service.course.CourseService;
import com.yf.dxapp.module.app.service.teacher.TeacherService;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * @author yxmds
 */
@Slf4j
@RestController
@RequestMapping("/index")
public class ApiAppIndexController extends ApiAppBaseController {

    @Resource
    private CourseService courseService;

    @Resource
    private AppConfigService appConfigService;

    @Resource
    private AppBannerService appBannerService;

    @Resource
    private BehaviorService behaviorService;

    @Resource
    private AppCourseComponent courseComponent;

    @Resource
    private AppNoticeService appNoticeService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private QiniuFileComponent qiniuFileComponent;


    /**
     * 1 小程序 2 app
     *
     * @param platform
     * @return
     */
    @RequestMapping("/banner/{platform}")
    @PermitAll
    public CommonResult banner(@PathVariable Integer platform) {
        List<AppBannerDO> list = appBannerService.findByType(BannerTypeEnum.APP_INDEX.getIndex());
        return success(list.stream().map(banner -> qiniuFileComponent.complementImgUrl(banner.getImg())).collect(Collectors.toList()));
    }

    /**
     * app首页
     *
     * @return
     */
    @RequestMapping("/index-content")
    @PermitAll
    public CommonResult appIndex() {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        AppIndexVo appIndexVo = new AppIndexVo();


        List<AppConfigDO> appConfigs = appConfigService.findConfigByKey(Arrays.asList("首页功能区", "精选课程标题", "精选课程编号", "推荐课程数","推荐课程标题","推荐导师编号","推荐导师标题"));
        // 功能图标区
        String appIndexVoStr = appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "首页功能区"))
                .map(AppConfigDO::getValue)
                .findFirst().orElse("");
        List<FunctionAreaVo> areas = JSON.parseArray(appIndexVoStr, FunctionAreaVo.class);
        appIndexVo.setFunctionArea(areas);
        // 课程标题
        appIndexVo.setSelectedLabelStr(appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "精选课程标题"))
                .map(AppConfigDO::getValue)
                .findFirst().orElse(""));
        // 精选课程id
        List<Long> selectedCourseIds = appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "精选课程编号"))
                .map(AppConfigDO::getValue)
                .map(Long::parseLong).collect(Collectors.toList());
        List<CourseDO> selectedCourses = courseService.getCourseByIds(selectedCourseIds);
        appIndexVo.setSelectedCourseVos(selectedCourses.stream().map(c -> courseComponent.convertCourse(c)).collect(Collectors.toList()));
        // 推荐课程（按照列表数据的推荐状态来）
        Integer recommendCourseLimit = appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "推荐课程数"))
                .map(AppConfigDO::getValue).map(Integer::parseInt).findFirst().orElse(5);
        List<AppCourseVo> recommendCourses = courseComponent.getRecommendCourseLit(loginUserId, recommendCourseLimit);
        appIndexVo.setRecommendedCourseVos(recommendCourses);
        // 课程标题
        appIndexVo.setRecommendedLabelStr(appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "推荐课程标题"))
                .map(AppConfigDO::getValue)
                .findFirst().orElse(""));
        // 推荐导师
        List<Long> teacherIds = appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "推荐导师编号"))
                .map(AppConfigDO::getValue)
                .map(Long::parseLong).collect(Collectors.toList());
        appIndexVo.setRecommendedTeacher(teacherService.getTeacherByList(teacherIds));
        // 导师标题
        appIndexVo.setRecommendedTeacherLabelStr(appConfigs.stream()
                .filter(config -> Objects.equals(config.getName(), "推荐导师标题"))
                .map(AppConfigDO::getValue)
                .findFirst().orElse(""));
        // 设置首页广告区
        List<AppBannerDO> bannerEntityList = appBannerService.findByType(BannerTypeEnum.APP_INDEX.getIndex());
        appIndexVo.setTopPictrue(bannerEntityList.stream().map(banner -> qiniuFileComponent.complementImgUrl(banner.getImg())).collect(Collectors.toList()));
        return success(appIndexVo);
    }

    /**
     * POST /api/app/mini/index/ad-meterial : 小程序首页广告轮播
     */
    @RequestMapping(value = "/ad-material",
            produces = {"application/json"},
            method = RequestMethod.POST)
    @PermitAll
    public CommonResult indexAdMaterial() {
        List<AppBannerDO> bannerEntityList = appBannerService.findByType(BannerTypeEnum.TOPCENTER.getIndex());
        if (CollectionUtils.isNotEmpty(bannerEntityList)) {
            List<String> imgs = bannerEntityList.stream().map(banner -> qiniuFileComponent.complementImgUrl(banner.getImg())).collect(Collectors.toList());
            return dataResult(imgs);
        }
        return dataResult(Collections.emptyList());
    }

    /**
     * app行为记录
     *
     * @param request
     * @return
     */
    @RequestMapping("/event-tracking")
    @PermitAll
    public CommonResult eventTracking(@RequestBody BehaviorRequest request) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId == null) {
            return success(false);
        }
        behaviorService.record(loginUserId, request.getRefId(), request.getType(), "请求地址：" + request.getUrl(), 10);
        return success(true);
    }

    /**
     * 返回通知信息
     *
     * @return
     */
    @RequestMapping("/get-notice")
    @PermitAll
    public CommonResult getNotice() {
        AppNoticePageReqVO req = new AppNoticePageReqVO();
        req.setStatus(AppStatusEnum.NORMAL.getIndex());
        req.setPageSize(1);
        PageResult<AppNoticeDO> result = appNoticeService.getAppNoticePage(req);
        return success(result);
    }

    @RequestMapping("/app-open-banner")
    @PermitAll
    public CommonResult getAppOpenBanner() {
        List<AppBannerDO> list = appBannerService.findByType(BannerTypeEnum.APP_OPEN.getIndex());
        return success(list.stream().map(banner -> {
            banner.setImg(qiniuFileComponent.complementImgUrl(banner.getImg()));
            return banner;
        }).collect(Collectors.toList()));
    }



}
